package com.baomidou.ant.service.impl;

import com.baomidou.ant.entity.*;
import com.baomidou.ant.mapper.ParentOrderMapper;
import com.baomidou.ant.service.*;
import com.baomidou.ant.utils.MyStringUtil;
import com.baomidou.ant.vo.request.*;
import com.baomidou.ant.vo.response.ResponseChildOrderInfoVo;
import com.baomidou.ant.vo.response.ResponseGetChartDataVo;
import com.baomidou.ant.vo.response.ResponseParentOrderVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jobob
 * @since 2022-03-18
 */
@Service
public class ParentOrderServiceImpl extends ServiceImpl<ParentOrderMapper, ParentOrder> implements IParentOrderService {
    @Autowired
    private IWorkOrderService workOrderService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private IProcessInfoService processInfoService;
    @Autowired
    private IReportOrderService reportOrderService;
    @Autowired
    private IPinLibraryService pinLibraryService;


    @Override
    public ParentOrder queryByLogNo(String lotNo) {
        QueryWrapper<ParentOrder> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("lot_no",lotNo);
        if(list(queryWrapper)==null||list(queryWrapper).size()==0){
            return null;
        } else
            return list(queryWrapper).get(0);
    }

    @Override
    public IPage<ResponseParentOrderVo> list(RequestListParentVo vo) {
        IPage<ParentOrder> iPage=new Page<>(vo.getDisplayStart(),vo.getDisplayLength());
        QueryWrapper<ParentOrder> queryWrapper=new QueryWrapper<>();
        if(ObjectUtils.isNotEmpty(vo.getLotNo())){
            queryWrapper.eq("lot_no",vo.getLotNo());
        }
        if(ObjectUtils.isNotEmpty(vo.getPinName())){
            PinLibrary pinLibrary=pinLibraryService.queryByPinName(vo.getPinName());
            queryWrapper.eq("pin_id",pinLibrary.getId());
        }
        if(ObjectUtils.isNotEmpty(vo.getProductType())){
            queryWrapper.eq("product_type",vo.getProductType());
        }
        if(ObjectUtils.isNotEmpty(vo.getCreateBy())){
            queryWrapper.eq("create_by",vo.getCreateBy());
        }
        if(ObjectUtils.isNotEmpty(vo.getStatus())){
            queryWrapper.eq("is_over",vo.getStatus());
        }
        //时间排序
        if(Objects.equals(vo.getSortStatus(), "desc")||ObjectUtils.isEmpty(vo.getSortStatus())){
            queryWrapper.orderByDesc("create_time");
        }
        if(Objects.equals(vo.getSortStatus(), "asc")){
            queryWrapper.orderByAsc("create_time");
        }
        //判断管理员级别
        SysUser user=userService.getById(vo.getUserId());
        if(Objects.equals(user.getType(), "1")){
            //管理员条件查询
            if(StringUtils.isNotBlank(vo.getOrderDept())){
                Integer deptId=deptService.queryByDeptName(vo.getOrderDept());
                queryWrapper.eq("order_dept",deptId);
            }
        } else if(Objects.equals(user.getType(), "0")){//二级管理员,只能看自己部门的
            queryWrapper.eq("order_dept",user.getDeptId());
        }else if(Objects.equals(user.getType(), "2")){//普通作业员,只能看到自己
            queryWrapper.eq("order_dept",user.getDeptId());
            //queryWrapper.like("worker_no",user.getLoginName());
        }
        Integer allTotal=list(queryWrapper).size();
        //得到结果集
        IPage<ParentOrder> orderPage=page(iPage,queryWrapper);
        //返回处理结果
        return orderPage.convert(order -> {
            ResponseParentOrderVo responseParentOrderVo=new ResponseParentOrderVo();
            BeanUtils.copyProperties(order,responseParentOrderVo);
            PinLibrary pinLibrary=pinLibraryService.getById(order.getPinId());
            responseParentOrderVo.setPinName(pinLibrary.getPinName());
            responseParentOrderVo.setAllTotal(allTotal);
            return responseParentOrderVo;
        });
    }

    @Override
    public String updateParent(RequestUpdateParentVo vo) {
        ParentOrder parentOrder=getById(vo.getId());
        String lotNo=parentOrder.getLotNo();
        boolean isChangeLotNo=false;
        if(!Objects.equals(parentOrder.getLotNo(), vo.getLotNo())){
            //更改了已有的lotNo,返回提示信息
            if(ObjectUtils.isNotEmpty(queryByLogNo(vo.getLotNo()))){
                return "300";
            }
            isChangeLotNo=true;
            lotNo=vo.getLotNo();
        }
        QueryWrapper<WorkOrder> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("parent_id",vo.getId());
        //更新父工单
        BeanUtils.copyProperties(vo,parentOrder);
        if(updateById(parentOrder)){
            //更新子工单
            List<WorkOrder> workOrderList=workOrderService.list(queryWrapper);
            for(WorkOrder workOrder:workOrderList){
                //更新工单号
                if(isChangeLotNo){
                    String[] numArr=workOrder.getOrderNum().split("#");
                    numArr[0]=lotNo;
                    StringBuilder newOrderNum=new StringBuilder();
                    for(int i = 0; i <numArr.length ; i++){
                        if (i==numArr.length-1){
                            newOrderNum.append(numArr[i]);
                        }else {
                            newOrderNum.append(numArr[i]).append("#");
                        }
                    }
                    workOrder.setOrderNum(newOrderNum.toString());
                }
                workOrder.setUnit(vo.getUnit());
                workOrder.setProductType(vo.getProductType());
                workOrder.setMaterialCode(vo.getMaterialCode());
                workOrder.setMaterialName(vo.getMaterialName());
                workOrder.setMaterialModel(vo.getMaterialModel());
                workOrder.setWorkshop(vo.getWorkshop());
                workOrderService.updateById(workOrder);
            }
            return "200";
        }else
            return "500";
    }

    @Override
    public List<ResponseChildOrderInfoVo> listChild(RequestChildOrderVo requestChildOrderVo) {
        ParentOrder parentOrder=queryByLogNo(requestChildOrderVo.getLotNo());
        QueryWrapper<WorkOrder> queryWrapper=new QueryWrapper<>();
        if(ObjectUtils.isNotEmpty(requestChildOrderVo.getChildNum())){
            queryWrapper.like("order_num", requestChildOrderVo.getChildNum());
        }
        queryWrapper.eq("parent_id",parentOrder.getId());
        List<WorkOrder> orderList=workOrderService.list(queryWrapper);
        List<ResponseChildOrderInfoVo> voList=new ArrayList<>();
        //得到数据
        for(WorkOrder workOrder:orderList){
            ResponseChildOrderInfoVo vo=new ResponseChildOrderInfoVo();
            BeanUtils.copyProperties(workOrder,vo);
            //当前工序
            if(Objects.equals(workOrder.getNowProcess(), 0)){
                vo.setNowProcess("无(已经完工)");
            }else {
                String nowProcess = processInfoService.getById(workOrder.getNowProcess()).getProcessName();
                vo.setNowProcess(nowProcess);
            }
            //完结的工序
            String over;
            if(Objects.equals(workOrder.getOverProcess(), "0")){
                over="暂未完结任何工序";
            }else {
                int[] overIds = MyStringUtil.toInt(workOrder.getOverProcess());
                String[] overProcess = new String[overIds.length];
                for (int i = 0; i < overIds.length; i++) {
                    if(overIds[i]==0){continue;}
                    ProcessInfo processInfo = processInfoService.getById(overIds[i]);
                    overProcess[i] = processInfo.getProcessName();
                }
                over = MyStringUtil.strToString(overProcess);
            }
            vo.setOverProcess(over);
            //所有工序
            int[] processIds= MyStringUtil.toInt(workOrder.getProcess());
            String[] processName=new String[processIds.length];
            //数量
            Integer[] reportAmount=new Integer[processIds.length];
            Integer[] reportBadAmount=new Integer[processIds.length];
            for(int i=0;i<processIds.length;i++){
                processName[i]=processInfoService.getById(processIds[i]).getProcessName();
                //查询上报数量条件构造
                QueryWrapper<ReportOrder> reportOrderQueryWrapper=new QueryWrapper<>();
                reportOrderQueryWrapper.eq("order_num",workOrder.getOrderNum());
                reportOrderQueryWrapper.eq("report_process",processIds[i]);
                List<ReportOrder> reportOrderList=reportOrderService.list(reportOrderQueryWrapper);
                if(reportOrderList==null||reportOrderList.size()==0){
                    reportAmount[i]=0;
                    reportBadAmount[i]=0;
                }else{
                    int amount=0;
                    int badAmount=0;
                    for(ReportOrder reportOrder:reportOrderList){
                        amount+=reportOrder.getReportAmount();
                        badAmount+=reportOrder.getBadAmount();
                    }
                    reportAmount[i]=amount;
                    reportBadAmount[i]=badAmount;
                }
            }
            //保存
            vo.setProcessName(processName);
            vo.setReportAmount(reportAmount);
            vo.setReportBadAmount(reportBadAmount);
            vo.setBadAmount(workOrder.getBadAmount());
            voList.add(vo);
        }
        return voList;
    }

    @Override
    public void addAmount(WorkOrder workOrder) {
        //工单结束,纳入父工单，只纳入已经审核完，即完工状态工单
        if (Objects.equals(workOrder.getOrderStatus(), "2")) {
            ParentOrder parentOrder = getById(workOrder.getParentId());
            parentOrder.setAmount(parentOrder.getAmount() + workOrder.getAmount());
//            QueryWrapper<ReportOrder> queryWrapper=new QueryWrapper<>();
//            queryWrapper.eq("order_num",workOrder.getOrderNum());
//            List<ReportOrder> reportOrderList=reportOrderService.list(queryWrapper);
            int badAmount = 0;
            badAmount = badAmount + workOrder.getBadAmount();
            parentOrder.setBadAmount(parentOrder.getBadAmount() + badAmount);
            //工单完结判断
            QueryWrapper<WorkOrder> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("parent_id",parentOrder.getId());
            queryWrapper.eq("order_status","2");
            if(workOrderService.list(queryWrapper).size()==parentOrder.getChildrenNum()){
                parentOrder.setOver(true);
            }
            updateById(parentOrder);
        }
    }

    @Override
    public ResponseGetChartDataVo getChartData(RequestGetChartDataVo vo) {
        ParentOrder parentOrder=queryByLogNo(vo.getLotNo());
        ResponseGetChartDataVo responseGetChartDataVo=new ResponseGetChartDataVo();
        //先获取工序名集合
        int[] ids=MyStringUtil.toInt(parentOrder.getProcess());
        String[] processNames=new String[ids.length+2];
        for(int i=0;i<ids.length;i++){
            processNames[i]=processInfoService.getById(ids[i]).getProcessName();
        }
        processNames[processNames.length-1]="未检录";
        processNames[processNames.length-2]="已完工";
        responseGetChartDataVo.setProcessNames(processNames);
        //获取各站待产数量
        Integer[] lotNum=new Integer[processNames.length];
        for(int j=0;j<processNames.length;j++){
            if(j==ids.length){//已完工的数据
                QueryWrapper<WorkOrder> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("parent_id", parentOrder.getId());
                queryWrapper.eq("now_process", 0);
                queryWrapper.eq("is_check",true);
                lotNum[j] = workOrderService.list(queryWrapper).size();
            }else if(j==processNames.length-1){//未检录数据
                QueryWrapper<WorkOrder> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("parent_id", parentOrder.getId());
                queryWrapper.eq("is_check",false);
                lotNum[j] = workOrderService.list(queryWrapper).size();
            }else {
                QueryWrapper<WorkOrder> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("parent_id", parentOrder.getId());
                queryWrapper.eq("now_process", ids[j]);
                queryWrapper.eq("is_check",true);
                lotNum[j] = workOrderService.list(queryWrapper).size();
            }
        }
        responseGetChartDataVo.setLotAmount(lotNum);
        //完成率统计
        QueryWrapper<WorkOrder> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("parent_id", parentOrder.getId());
        List<WorkOrder> workOrderList=workOrderService.list(queryWrapper);
        //总数
        Integer allAmount=workOrderList.size();
        queryWrapper.eq("order_status","2");
        //完成与未完成数量
        Integer completionAmount=workOrderService.list(queryWrapper).size();
        Integer notCompletionAmount=allAmount-completionAmount;
        responseGetChartDataVo.setCompletionAmount(completionAmount);
        responseGetChartDataVo.setNotCompletionAmount(notCompletionAmount);
        responseGetChartDataVo.setAllTotal(allAmount);
        //近七日上报数量统计
        Integer[] dateAmount=new Integer[7];
        for(int l=0;l<dateAmount.length;l++){
            QueryWrapper<ReportOrder> reportOrderQueryWrapper=new QueryWrapper<>();
            reportOrderQueryWrapper.like("order_num",parentOrder.getLotNo());
            //六日数据
            if(l==0){
                reportOrderQueryWrapper.apply("DateDiff(dd,create_time,getdate())=6");
//                reportOrderQueryWrapper.apply("CONVERT(varchar(30),create_time,102 )  = CONVERT(varchar(30),getdate() - 6,102)");
            }else if(l==1){
                reportOrderQueryWrapper.apply("DateDiff(dd,create_time,getdate())=5");
            }else if(l==2){
                reportOrderQueryWrapper.apply("DateDiff(dd,create_time,getdate())=4");
            }else if(l==3){

                reportOrderQueryWrapper.apply("DateDiff(dd,create_time,getdate())=3");
            }else if(l==4){
                reportOrderQueryWrapper.apply("DateDiff(dd,create_time,getdate())=2");
            }else if(l==5){
                reportOrderQueryWrapper.apply("DateDiff(dd,create_time,getdate())=1");
            }else {
                reportOrderQueryWrapper.apply("DateDiff(dd,create_time,getdate())=0");
            }
            dateAmount[l]=reportOrderService.list(reportOrderQueryWrapper).size();
        }
        responseGetChartDataVo.setDateAmount(dateAmount);
        return responseGetChartDataVo;
    }

    @Override
    public String addFromKingdee(RequestAddOrderFromERPVo vo) {
        //判断是否有相同单号
        if(ObjectUtils.isNotEmpty(queryByLogNo(vo.getFbillNo()))){
            return "HAVING_IT";
        }
        //部门信息查询
        SysDept dept=deptService.queryOne(vo.getFprdOrgId());
        if(dept==null){
            return "NOT_FOUND_DEPT";
        }
        //产品信息查询
        PinLibrary pin=pinLibraryService.queryOne(dept.getId(),vo.getFspecification(),vo.getFmaterialId());
        if(pin==null){
            return "NOT_FOUND_PIN";
        }
        SysUser user=userService.getById(vo.getUserId());
        //数据写入
        ParentOrder parentOrder=new ParentOrder();
        parentOrder.setTotalAmount(vo.getFqty());
        parentOrder.setCreateBy(user.getUserName());
        parentOrder.setOrderDept(dept.getId());
        parentOrder.setLotNo(vo.getFbillNo());
        parentOrder.setProcess(pin.getProcess());
        parentOrder.setAcceptAmount(vo.getAcceptAmount());
        parentOrder.setPinId(pin.getId());
        parentOrder.setProductType(pin.getProductType());
        int childrenNum=(int)Math.ceil((double) vo.getFqty() /(double)vo.getAcceptAmount());
        parentOrder.setChildrenNum(childrenNum);
        //指派人员
        String[] processList=pin.getProcess().split(",");
        String[] workerList=new String[processList.length];
        Arrays.fill(workerList, "");
        if(save(parentOrder)){
            workOrderService.addWorkOrder(parentOrder,workerList);
            return "ADD_SUCCESS";
        }else
            return "ADD_FAILURE";
    }

    @Override
    public String saveOrder(RequestSaveOrderVo requestSaveOrderVo) {
        //判断是否有相同工单号/lotNo
        if(ObjectUtils.isNotEmpty(queryByLogNo(requestSaveOrderVo.getLotNo()))){
            return "300";
        }
        //判断是否工序是否有误
        PinLibrary pinLibrary=pinLibraryService.getById(requestSaveOrderVo.getPinId());
        if(!Objects.equals(requestSaveOrderVo.getProcess(),pinLibrary.getProcess())){
            return "400";        }
        ParentOrder parentOrder=new ParentOrder();
        BeanUtils.copyProperties(requestSaveOrderVo,parentOrder);
        //设置部门
        parentOrder.setOrderDept(requestSaveOrderVo.getDeptId());
        //生成子工单数量
        int childrenNum=(int)Math.ceil((double) parentOrder.getTotalAmount() /(double)parentOrder.getAcceptAmount());
        parentOrder.setChildrenNum(childrenNum);
        //雪花算法生成编号
        //workOrder.setOrderNum("M"+ IdWorker.getId());
        //工单创建人
        parentOrder.setCreateBy(userService.getById(requestSaveOrderVo.getUserId()).getUserName());
        if(save(parentOrder)){
            workOrderService.addWorkOrder(parentOrder,requestSaveOrderVo.getWorkerList());
            return "200";
        }else
            return "500";
    }


}
